<template> 
  <qh-page-view :showNavbar="false" bgColor="#fff">
    <view class="fixed-header" :style="headerStyle">
      <uni-status-bar></uni-status-bar>
      <view class="search-box flex-cn">
        <view class="navbar-left flex-cn" style="flex: 1" @click="backHome">
          <view
            style="width: 100rpx; text-align: center; color: #fff"
            class="qh-rt-single qh-rt-zuo-zuo navbar-back-icon"
            :class="{ 'icon-dark': isScrolled }"
          >
          </view>
        </view>

        <view
          class="header-title"
          style="color: #fff; font-weight: 600"
          :class="{ 'text-dark': isScrolled }"
        >
          {{ title }}
        </view>
        <view style="width: 320rpx; flex: 1"></view>
      </view>
    </view>

    <view class="benner_box">
      <view class="benner_box_top">
        <img
          class="benner_box_top_img"
          src="https://safood-1317438654.cos.ap-guangzhou.myqcloud.com/tempImage/1733989391675a940fb04d9.png"
          alt=""
        />
        <view class="benner_box_top_text">{{ titleName }}</view>
      </view>

      <view class="brand-image" v-if="productList.length > 0">
        <img :src="suggest_obj.goods_image" alt="" />

        <view class="brand-footer" v-if="productList.length > 2">
          <view class="brand-footer-item">
            <view class="brand-footer-item-left">
              <image
                class="brand-footer-item-left-img"
                :src="suggest_obj.goods_image"
                loading="lazy"
                alt="aspectFill"
              />

              <!--<image
                class="brand-footer-item-left-img-bottom"
                src="https://safood-1317438654.cos.ap-guangzhou.myqcloud.com/tempImage/1733992948675aa1f4c3b88.png"
                alt=""
              />-->
            </view>

            <view class="brand-footer-item-right">
              <view>{{ suggest_obj.goods_name }}</view>
              <image
                style="width: 112rpx; height: 34rpx; margin: 20rpx 0"
                src="https://safood-1317438654.cos.ap-guangzhou.myqcloud.com/tempImage/17338083046757d0b0aba4f.png"
                alt=""
              />

              <view
                style="
                  position: relative;
                  display: flex;
                  flex-direction: column;
                "
              >
                <image
                  style="width: 364rpx; height: 60rpx"
                  src="https://safood-1317438654.cos.ap-guangzhou.myqcloud.com/tempImage/1733994987675aa9ebe15b4.png"
                  alt=""
                ></image>
                <view
                  style="
                    position: absolute;
                    top: 50%;
                    left: 30%;
                    transform: translate(-50%, -60%);
                    color: #f4d2ab;
                  "
                >
                  <text style="font-size: 22rpx">抢购价￥</text>
                  <text style="font-weight: 600">{{
                    suggest_obj.online_price
                  }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="obj_bubble-outer">
        <view class="obj_bubble-container">
          <view class="obj_switch-container">
            <view class="obj_bubble-close-img" @tap="handleSwitchChange">
              <text
                class="feiIconfont icon-gengduo1"
                style="color: #fff"
              ></text>
            </view>
          </view>

          <view v-if="showBubble" class="obj_bubble-box">
            <view
              class="obj_bubble-content"
              :class="{
                'obj_bubble-animated': showBubble && !slideOut,
                'obj_bubble-slide-out': slideOut,
              }"
              :style="bubbleStyle"
              @click.stop
            >
              <view
                class="obj_bubble-grid"
                :class="{ 'obj_bubble-grid-two': twoColumns }"
              >
                <view
                  v-for="(item, index) in customBubbleItems"
                  :key="index"
                  class="obj_bubble-item"
                  :class="{ 'obj_bubble-active': item.active }"
                  @tap="handleBubbleClick(index)"
                >
                  {{ item.class_name }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <view>
        <brand_product
          :products="productList"
          @item-click="handleProductClick"
        ></brand_product>
      </view>

      <view class="brand-details-series-title">
        <image
          src="https://safood-1317438654.cos.ap-guangzhou.myqcloud.com/tempImage/1734002876675ac8bcdc835.png"
          alt=""
        ></image>
      </view>

      <view class="brand-details-series-content">
        <brand_series
          :productList="brand_serie_list"
          @product-click="handleProductOneClick"
        ></brand_series>
      </view>

      <view class="brand-details-series-content">
        <brand_goods
          :products="productgGodsList"
          @product-click="handleProductGoodsClick"
        ></brand_goods>
      </view>

      <view>
        <brand_series
          :productList="productListOne"
          @product-click="handleProductOneClick"
        ></brand_series>

        <!-- 加载更多提示 -->
        <view class="load-more" v-if="productListOne.length > 0">
          <view v-if="isLoading" class="loading">加载中...</view>
          <view v-else-if="!pageInfo.hasMore" class="no-more"
            >没有更多数据了</view
          >
          <view
            v-else
            @click="() => getBrandHotList(true)"
            class="load-more-btn"
          >
            点击加载更多
          </view>
        </view>
      </view>
    </view>
  </qh-page-view>
</template>

<script>
import brand_product from "./components/brand_product.vue";
import brand_series from "./components/brand_series.vue";
import brand_goods from "./components/brand_goods.vue";
export default {
  components: { brand_product, brand_series, brand_goods },
  data() {
    return {
      titleName: "",
      title: "品牌专区",
      isScrolled: false,
      isTop: true,
      showBubble: false, //盒子的开关
      slideOut: false,
      twoColumns: true,
      offsetTop: "180rpx",
      offsetLeft: "60rpx",
      customBubbleItems: [
        { text: "臻味环球经典系列", active: true },
        { text: "臻味环球臻选系列", active: false },
        { text: "臻味环球祝福系列", active: false },
        { text: "臻味常规品系列", active: false },
        { text: "臻味木系列", active: false },
        { text: "臻味高端木本油", active: false },
      ],
      productListOne: [],
      brand_serie_list: [],
      productList: [],
      class_id: "",
      suggest_obj: {},
      productgGodsList: [],
      brand_id: "",
      pageInfo: {
        page: 1,
        limit: 10,
        hasMore: true,
      },
      isLoading: false,
    };
  },
  computed: {
    headerStyle() {
      return `background-image: ${
        this.isTop
          ? 'url("https://safood-1317438654.cos.ap-guangzhou.myqcloud.com/tempImage/17337434366756d34caea20.png")'
          : "none"
      }`;
    },
    styleColor() {
      return `color: ${this.isTop ? "#fff" : "#000 "}`;
    },
    bubbleStyle() {
      return {
        position: "absolute",
        top: this.offsetTop,
        left: this.offsetLeft,
        transform: "translate3d(0,0,0)",
        zIndex: 1000,
      };
    },
  },
  onLoad(options) {
    console.log("Received options:", options.brand_id);
    if (options.brand_id) {
      const brandId = options.brand_id;
      this.getBrandClassify(brandId);
      this.brand_id = options.brand_id;
      this.getBrandSeries();
      this.getBrandHotList();
    }
  },
  methods: {
    handleProductOneClick(item) {
      uni.navigateTo({
        url: "/pages/mer/goods/details/details?id=" + item.id,
      });
    },
    handleProductGoodsClick(item) {
      uni.navigateTo({
        url: "/pages/mer/goods/details/details?id=" + item.id,
      });
      console.log("商品被点击:", item);
    },
    // 爆款系列的前两个
    handleProductSeriesClick(item) {
      uni.navigateTo({
        url: "/pages/mer/goods/details/details?id=" + item.id,
      });
    },
    handleProductClick(item) {
      // 处理商品点击事件
      console.log("商品被点击:", item);
    },
    backHome() {
      uni.navigateBack();
    },
    onPageScroll(e) {
      this.isScrolled = e.scrollTop > 0;
      this.isTop = e.scrollTop === 0;
    },
    handleSwitchChange() {
      if (!this.showBubble) {
        this.openBubble();
      } else {
        this.closeBubble();
      }
    },
    openBubble() {
      this.showBubble = true;
      this.slideOut = false;
    },
    closeBubble() {
      this.slideOut = true;
      setTimeout(() => {
        this.showBubble = false;
        this.slideOut = false;
      }, 300);
    },
    async handleBubbleClick(index) {
      uni.showLoading({
        title: "加载中...",
        mask: true,
      });

      try {
        this.customBubbleItems = this.customBubbleItems.map((item, i) => ({
          ...item,
          active: i === index,
        }));
        const activeItem = this.customBubbleItems[index];

        this.class_id = activeItem.class_id;
        this.titleName = activeItem.class_name;

        this.resetPagination();
        // 因为这两个方法可能是异步的，所以添加 await
        await Promise.all([this.getBrandSeries(), this.getBrandHotList()]);
        this.handleSwitchChange() // 关闭气泡
      } catch (error) {
        console.error("加载失败:", error);
        uni.showToast({
          title: "加载失败",
          icon: "none",
        });
      } finally {
        // 无论成功还是失败都关闭loading
        uni.hideLoading();
      }
    },

    // label标签顶部
    async getBrandClassify(brandId) {
      console.log("Getting brand details for ID:", brandId);
      try {
        const res = await this.$request(
          "SmallProgramApi/NewYear/getClassByBrand",
          {
            brand_id: brandId,
            store_id: this.$store.mallStoreId,
            merchant_id: 1,
          }
        );
        // 处理返回数据
        if (res.data) {
          this.titleName = res.data[0].class_name;
          this.customBubbleItems = res.data.map((item, index) => ({
            ...item,
            active: index === 0, // 第一个为 true，其他为 false
          }));

          this.class_id = res.data[0].class_id;
          console.log("数据", res.data);
        }
      } catch (error) {
        console.log("错误", error);
      }
    },

    //推荐的系列
    async getBrandSeries() {
      try {
        const res = await this.$request(
          "SmallProgramApi/NewYear/getHostGoodsLimit",
          {
            brand_id: this.brand_id,
            store_id: this.$store.mallStoreId,
            merchant_id: 1,
            source_type: 1,
            class_id: this.class_id,
          }
        );
        // 处理返回数据
        if (res.data) {
          this.suggest_obj = res.data[0];
          // 从索引1开始截取数组（跳过第一个元素）
          this.productList = res.data.slice(1);
          console.log(this.suggest_obj, "suggest_objsuggest_obj");
          console.log("推荐的系列推荐的系列推荐的系列", res.data);
        }
      } catch (error) {
        console.log("错误", error);
      }
    },

    // 获取明星爆款列表
    async getBrandHotList(isLoadMore = false) {
      if (this.isLoading || (!isLoadMore && !this.pageInfo.hasMore)) return;

      try {
        this.isLoading = true;
        const res = await this.$request(
          "SmallProgramApi/NewYear/getBrandGoodsList",
          {
            brand_id: this.brand_id,
            store_id: this.$store.mallStoreId,
            merchant_id: 1,
            source_type: 1,
            class_id: this.class_id,
            page: this.pageInfo.page,
            limit: this.pageInfo.limit,
          }
        );

        if (res.data) {
          // 处理前6个商品的特殊显示
          if (this.pageInfo.page === 1) {
            this.brand_serie_list = res.data.slice(0, 2);
            this.productgGodsList = res.data.slice(2, 6);
            // 剩余的商品放入明星爆款列表
            this.productListOne = res.data.slice(6);
          } else {
            // 加载更多时直接追加到明星爆款列表
            this.productListOne = [...this.productListOne, ...res.data];
          }

          // 更新分页信息
          this.pageInfo.hasMore = res.data.length >= this.pageInfo.limit;
          if (isLoadMore) {
            this.pageInfo.page++;
          }
        }
      } catch (error) {
        console.log("错误", error);
      } finally {
        this.isLoading = false;
      }
    },

    // 重置分页
    resetPagination() {
      this.pageInfo = {
        page: 1,
        limit: 10,
        hasMore: true,
      };
      this.productListOne = [];
    },
  },
};
</script>

<style lang="scss" scoped>
.brand-details-series-title {
  padding: 0 20rpx;
  image {
    height: 168rpx;
    width: 100%;
  }
}

.brand-image {
  height: 960rpx;
  width: 100%;
  position: relative;
  img {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
  }

  .brand-footer {
    position: absolute;
    bottom: 40rpx;
    left: 50%;
    transform: translateX(-50%);

    .brand-footer-item {
      height: 193rpx;
      width: 709rpx;
      margin: 0 20rpx;
      background-image: url("https://safood-1317438654.cos.ap-guangzhou.myqcloud.com/tempImage/1733991633675a9cd1c4413.png");
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .brand-footer-item-left {
        margin: 0 20rpx;
        position: relative;
        width: 300rpx;

        .brand-footer-item-left-img {
          height: 195rpx;
          width: 210rpx;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%) translateZ(0);
          will-change: transform;
          backface-visibility: hidden;
          transform-style: preserve-3d;
          transition: transform 0.3s ease;
          image-rendering: -webkit-optimize-contrast;
          z-index: 999;
        }
      }

      .brand-footer-item-right {
        width: 414rpx;
        height: 100%;
        display: flex;
        justify-content: center;
        flex-direction: column;

        // 添加文本溢出处理
        view:first-child {
          // 商品名称样式
          width: 100%;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          font-size: 28rpx;
          color: #333;
          padding-right: 20rpx; // 防止文字贴边
          box-sizing: border-box;
        }
      }
    }
  }
}

.obj_bubble-outer {
  position: absolute;
  left: 40rpx;
  top: 50rpx;
  z-index: 100;
}

.obj_bubble-container {
  position: relative;
}

.obj_switch-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  border-radius: 10rpx;
  background-color: gray;
  width: 56rpx;
  height: 56rpx;
  margin-left: 0;
}

.obj_bubble-box {
  position: absolute;
  left: 0;
  top: 70rpx;
  width: 100%;
}

.obj_bubble-content {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin: 0;
  position: absolute;
  left: 0;
  top: 0;
  min-width: 500rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.12);
  transform-origin: top left;
  transform: scale(0.5);
  opacity: 0;

  &::before {
    content: "";
    position: absolute;
    top: -12rpx;
    left: 20rpx;
    border-left: 12rpx solid transparent;
    border-right: 12rpx solid transparent;
    border-bottom: 12rpx solid #fff;
    filter: drop-shadow(0 -2rpx 2rpx rgba(0, 0, 0, 0.08));
  }
}

.obj_bubble-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  width: 100%;
}

.obj_bubble-item {
  height: 64rpx;
  width: auto;
  min-width: 250rpx;
  padding: 0 30rpx;
  background-color: #f5f5f5;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #333;
  transition: all 0.3s;
}

.obj_bubble-active {
  background: #8b5e3c;
  color: #fff;
}

@keyframes bubbleIn {
  from {
    transform: translateY(-20rpx) scale(0.5);
    opacity: 0;
  }
  to {
    transform: translateY(0) scale(1);
    opacity: 1;
  }
}

@keyframes bubbleOut {
  from {
    transform: translateY(0) scale(1);
    opacity: 1;
  }
  to {
    transform: translateY(-20rpx) scale(0.5);
    opacity: 0;
  }
}

.obj_bubble-animated {
  animation: bubbleIn 0.3s ease forwards;
}

.obj_bubble-slide-out {
  animation: bubbleOut 0.3s ease forwards;
}

.obj_bubble-close-img {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 56rpx;
  height: 56rpx;
  transition: transform 0.3s ease;
  transform: rotate(0deg);

  &.active {
    transform: rotate(180deg);
  }
}

.benner_box {
  background-color: #fff;
  position: relative;
  width: 100%;
  margin-top: calc(88rpx + 44px);
  padding-bottom: env(safe-area-inset-bottom);
  background-color: #fff;
}

.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 999;
  height: calc(88rpx + 44px);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  background-color: #ffffff;
}

@media screen and (device-width: 375px) and (device-height: 667px),
  /* iPhone 6/7/8 */ screen and (device-width: 414px) and (device-height: 736px),
  /* iPhone 6/7/8 Plus */ screen and (device-width: 360px) and (device-height: 640px) /* 常见安卓机型 */ {
  .benner_box {
    margin-top: 88rpx;
    background-color: #fff;
  }

  .fixed-header {
    height: 88rpx;
    padding-top: 0;
  }
}

.benner_box_top {
  position: relative;
  font-size: 0;
}

.benner_box_top_img {
  height: 128rpx;
  width: 100%;
  display: block;
  vertical-align: top;
}

.benner_box_top_text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #855a37;
  font-size: 48rpx;
  font-weight: 600;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.load-more {
  text-align: center;
  padding: 20rpx 0;
  color: #666;
  font-size: 28rpx;

  .loading {
    color: #999;
  }

  .no-more {
    color: #999;
  }

  .load-more-btn {
    display: inline-block;
    padding: 15rpx 40rpx;
    background: #f5f5f5;
    border-radius: 30rpx;
    color: #666;

    &:active {
      opacity: 0.8;
    }
  }
}
</style>